export default {
  namespaced: true, // 命名空间，要加上，用于区分不同的module
  state: {
    cartList: []
  },
  getters: {
    getCartList (state, val) {
      return state.cartList
    },
    isAllChecked (state) {
      //every 所有为真，则为真
      return state.cartList.every(item => item.state)
    },

    // 计算总价
    TotalPrice (state) {
      return state.cartList
        .filter(item => item.state)
        .reduce((total, item) => total + item.number * item.price, 0)
    },
    /* 总数量 */
    tatalNum (state) {
      return state.cartList.reduce((total, item) => total + item.number, 0)
    }
  },
  mutations: {
    /* 加入购物车 val=>{proid,number}*/
    addCart (state, val) {
      //   查找cartList中是否存在相同的商品
      const oldGoods = state.cartList.find(item => item.proid === val.proid)
      if (oldGoods) {
        //    找到了
        oldGoods.number += val.number
      } else {
        state.cartList.push(val)
      }
    },
    /* 改变单选状态 val=>{proid,state}*/
    changeSelect (state, val) {
      const oldGoods = state.cartList.find(item => item.proid === val.proid)
      if (oldGoods) {
        oldGoods.state = val.state
      }
    },
    /* 全选 val=>state */
    selectAll (state, val) {
      state.cartList.forEach(item => {
        item.state = val
      })
    },
    /* 修改数量 val=>{proid,number}*/
    changeNum (state, val) {
      const oldGoods = state.cartList.find(item => item.proid === val.proid)
      if (oldGoods) {
        oldGoods.number = val.number
      }
    },
    // 删除商品  val=>proid
    del (state, val) {
      state.cartList = state.cartList.filter(item => item.proid !== val)
    }
  }
}
